package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 添加预约
     *
     * @param orderSettings
     * @return
     */
    @Override
    public Result add(List<OrderSetting> orderSettings) {
        //如果没有数据
        if (orderSettings == null || orderSettings.size() <= 0)
            throw new RuntimeException(MessageConstant.IMPORT_ORDERSETTING_FAIL);

        for (OrderSetting orderSetting : orderSettings) {
            //判断当前日期是否已经进行了设置
            Integer countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());

            if (countByOrderDate > 0) {
                //已经进行了预约设置,执行更新操作
                orderSettingDao.editNumberByOrderDate(orderSetting);
            } else {
                //没有进行预约设置,进行添加操作
                orderSettingDao.save(orderSetting);
            }

        }

        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    @Override
    public Result getOrderSettingByMonth(String date) {

        if (date == null || "".equals(date))
            throw new RuntimeException(MessageConstant.GET_ORDERSETTING_FAIL);

        String begin = date + "-01"; //xxxx-xx-01

        String end = date + "-31";//xxxx-xx-31

        List<Map> list = orderSettingDao.findOrderSettingByMonth(begin, end);
        if (list == null || list.size() <= 0)
            throw new RuntimeException(MessageConstant.GET_ORDERSETTING_FAIL);


        return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
    }

    @Override
    public Result editOrderSetting(OrderSetting orderSetting) {

        if (orderSetting == null)
            throw new RuntimeException(MessageConstant.ORDERSETTING_FAIL);

        //判断当前日期是否已经进行了设置
        Integer countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());

        if (countByOrderDate > 0) {
            //已经进行了预约设置,执行更新操作
            orderSettingDao.editNumberByOrderDate(orderSetting);
        } else {
            //没有进行预约设置,进行添加操作
            orderSettingDao.save(orderSetting);
        }

        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }


}
